package com.shixun.milktea.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Zourongsheng
 * @version 1.0
 * @date 2022/6/9 19:29
 */
@Component
@Data
@ConfigurationProperties(prefix = "jwt")//注入参数
public class JwtUtil {
    static final String USER_NAME="username";//用户昵称
    static final String TOKEN_SUB="uuid";
    private String secret;//盐
    private Long validity;//有效期

    /**
     * 生成token
     * @param username
     * @return
     */
    public String generateToken(String username){
        //header
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        //payload:签发时间
        long created = System.currentTimeMillis();
        Date issued = new Date(created);
        //payload:过期时间
        long expires = created+ validity;
        Date expiration = new Date(expires);
        //私有声明
        Map<String,Object> cliams = new HashMap<>();
        cliams.put(TOKEN_SUB, UUID.randomUUID());
        cliams.put(USER_NAME,username);//添加用户id
        return Jwts.builder()
                .setHeader(header)
                .setClaims(cliams)
                .setIssuedAt(issued)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return 身份信息
     */
    public Claims parseToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    /**
     * 判断token是否有效
     * @param token
     * @return
     */
    public  boolean isExpires(String token){

        if (token ==null) return true;
        if (token !=null){
            try {
                Claims claims = parseToken(token);
            }catch (Exception e){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取token用户ID
     * @param token
     * @return
     */
    public String getUserName(String token){
        Claims claims = parseToken(token);
        return (String)claims.get(USER_NAME);
    }

    /**
     * 验证token是否合法
     * @param accessToken
     * @param validityToken
     * @return
     */
    public boolean validityToken(String accessToken,String validityToken){
        /*
        将请求token与生成的token比较
        两个token是否一致，防伪造
         */
        if (validityToken !=null){
            if (accessToken.equals(validityToken)){
                return true;
            }
        }
        return false;
    }
}
